const redis = require( './redis_utils' );
const cacheKey = require( './cache_key_utils' );
const securityToken = require( '../models/security_token' );
const akUtils = require( './ak_utils' );

function getApiKeyByToken( callbackGet, token ) {

    var key = cacheKey.tokenKey( token );

    var userInfo = {};

    var getKeyValueFromRedis = function ( callback ) {
        redis.get( key, callback );
    };

    var isReturnKeyValue = function ( result, callback ) {
        if ( !result ) {
            securityToken.getByKey( callback, key );
        } else {

            var params = result.toString().split( ',' );

            if ( params.length == 4 ) {
                userInfo.userId = params[ 0 ];
                userInfo.ak = params[ 3 ];
                callbackGet( userInfo );
                return;
            } else {
                callbackGet( userInfo );
                return;
            }
        }
    };

    var setKeyValueToRedis = function ( keyValue, callback ) {
        if ( !keyValue.rows || !keyValue.rows[ 0 ] ) {
            callbackGet( userInfo );
            return;
        } else {
            value = keyValue.rows[ 0 ].value.split( ',' );
            if ( value.length == 4 ) {
                userInfo.userId = value[ 0 ];
                userInfo.ak = value[ 3 ];
            }
            redis.set( key, keyValue.rows[ 0 ].value, callback );
        }
    };

    var callback = function ( err, result ) {
        if ( err ) {
            console.error( { 'code': 1, 'msg': '写入redis失败' } );
        }
        callbackGet( userInfo );
    };

    var functionList = [ getKeyValueFromRedis, isReturnKeyValue, setKeyValueToRedis ];

    async.waterfall( functionList, callback );
}

exports.getApiKeyByToken = getApiKeyByToken;
